<template>
    <div class="firmware-update-container">
        <div class="update-header">
            <h2>更新固件</h2>
            <p>为设备上传和安装新的固件版本</p>
        </div>
        
        <div class="upload-section">
            <h3>固件上传</h3>
            <!-- 自定义文件选择器UI -->
            <div class="custom-upload-dragger" @click="openFileSelector">
                <p class="upload-drag-icon">
                    <a-icon type="inbox" />
                </p>
                <p class="upload-text">点击选择固件文件</p>
                <p class="upload-hint">
                    支持 .bin, .hex, .img 格式的固件文件
                </p>
            </div>
            
            <div v-if="selectedFile" class="upload-info">
                <h4>已选择文件：</h4>
                <div class="file-item">
                    <a-icon type="file" />
                    <span class="file-name">{{ selectedFile.name }}</span>
                    <span class="file-path">{{ selectedFile.path }}</span>
                    <a-button type="link" size="small" @click="clearSelectedFile">
                        <a-icon type="delete" />
                    </a-button>
                </div>
            </div>

            <a-form-item label="或输入固件路径" style="margin-top: 16px;">
                <a-input v-model="firmwarePath" placeholder="请输入固件文件的本地路径或URL" @input="handlePathInput" />
            </a-form-item>
        </div>
        
        <div class="update-actions">
            <a-button 
                type="primary" 
                size="large" 
                icon="upload"
                :disabled="!canUpdate"
                :loading="updating"
                @click="startUpdate"
            >
                开始更新固件
            </a-button>
        </div>
        
        <div v-if="updating" class="update-progress">
            <a-progress 
                :percent="updateProgress" 
                :status="updateProgress === 100 ? 'success' : 'active'"
                stroke-color="#1890ff"
            />
            <p class="progress-text">{{ progressText }}</p>
        </div>

        <!-- 更新历史记录 -->
        <div class="history-section">
            <h3>更新历史</h3>
            <a-list 
                :data-source="updateHistory" 
                :locale="{ emptyText: '暂无更新记录' }"
            >
                <a-list-item slot="renderItem" slot-scope="item">
                    <a-list-item-meta>
                        <div slot="title">
                            {{ item.device }}
                            <a-tag :color="item.status === 'success' ? 'green' : 'red'">
                                {{ item.status === 'success' ? '成功' : '失败' }}
                            </a-tag>
                        </div>
                        <div slot="description">
                            <div>固件: {{ item.firmware }}</div>
                            <div>{{ item.time }}</div>
                        </div>
                    </a-list-item-meta>
                </a-list-item>
            </a-list>
        </div>
    </div>
</template>

<script>
import { mapGetters } from 'vuex'
import DeviceTabManager from '@/api/TabManager/DeviceTabManager'
import { openFileDialog } from '@/api/TabAxios/base'

export default {
    name: 'FirmwareUpdate',
    props: {
        ipAddress: {
            type: String,
            required: true
        },
        port: {
            type: String,
            required: true
        }
    },
    data() {
        return {
            selectedFile: null,
            firmwarePath: '',
            updating: false,
            updateProgress: 0,
            progressText: '准备更新...',
            statusCheckTimer: null,
            deviceTabManager: new DeviceTabManager(),
            updateHistory: [] // 新增：更新历史记录
        }
    },
    computed: {
        ...mapGetters('groupTree', ['selectedDeviceInfo']),
        canUpdate() {
            return (this.selectedFile || this.firmwarePath.trim() !== '') && this.selectedDeviceInfo
        }
    },
    beforeDestroy() {
        this.clearStatusCheck()
    },
    methods: {
        // 开始更新固件
        async startUpdate() {
            if (!this.selectedDeviceInfo) {
                this.$message.error('请先选择设备')
                return
            }

            // 验证网络参数
            if (!this.ipAddress || !this.ipAddress.trim()) {
                this.$message.error('请先输入IP地址')
                return
            }

            if (!this.port || !this.port.trim()) {
                this.$message.error('请先输入端口号')
                return
            }

            try {
                this.updating = true
                
                // 判断固件来源
                let firmwareFilePath = ''
                
                // 优先使用手动输入的路径
                if (this.firmwarePath.trim()) {
                    console.log('📁 [FirmwareUpdate] 使用手动输入的固件路径:', this.firmwarePath)
                    this.$message.info('使用指定路径的固件文件')
                    firmwareFilePath = this.firmwarePath.trim()
                } else if (this.selectedFile) {
                    // 使用上传的文件的绝对路径
                    if (!this.selectedFile.path) {
                        this.$message.error('无法获取文件的绝对路径')
                        this.updating = false
                        return
                    }
                    console.log('📁 [FirmwareUpdate] 使用上传的固件文件路径:', this.selectedFile.path)
                    this.$message.info('使用上传的固件文件')
                    firmwareFilePath = this.selectedFile.path
                } else {
                    this.$message.error('请选择固件文件或输入固件路径')
                    this.updating = false
                    return
                }

                // 构建更新参数
                const deviceParams = {
                    filepath: firmwareFilePath,
                    ip: this.ipAddress.trim(),
                    port: this.port.trim(),
                    gatewayType: this.selectedDeviceInfo.gatewayType
                }
                
                console.log('🔄 [FirmwareUpdate] 开始更新固件:', deviceParams)
                const response = await this.deviceTabManager.updateFirmware(JSON.stringify(deviceParams))

                if (response.code === 0) {
                    this.$message.info('固件更新指令已发送，正在等待更新...')
                    this.startStatusCheck()
                } else {
                    this.handleUpdateFailure('固件更新指令发送失败: ' + response.msg)
                }
            } catch (error) {
                this.handleUpdateFailure('固件更新失败: ' + error.message)
            }
        },

        // 打开文件选择器
        async openFileSelector() {
            try {
                console.log('📁 [FirmwareUpdate] 打开文件选择器')
                
                // 调用CefSharp的文件选择器接口
                const response = await openFileDialog({
                    title: '选择固件文件',
                    filter: 'Firmware Files|*.bin;*.hex;*.img|All Files|*.*',
                    multiSelect: false
                })
                
                if (response.code === 0 && response.data) {
                    const data = JSON.parse(response.data)
                    const filePath = data.filePath
                    
                    // 验证文件扩展名
                    const fileName = data.fileName
                    const isValidType = fileName.endsWith('.bin') || fileName.endsWith('.hex') || fileName.endsWith('.img')
                    
                    if (!isValidType) {
                        this.$message.error('只支持 .bin, .hex, .img 格式的固件文件！')
                        return
                    }
  
                    // 创建文件对象
                    this.selectedFile = {
                        name: fileName,
                        path: filePath
                    }
                    
                    console.log('📁 [FirmwareUpdate] 已选择文件:', this.selectedFile)
                    this.$message.success(`已选择文件: ${fileName}`)
                    
                    // 如果有手动输入的路径，给出提示
                    if (this.firmwarePath.trim()) {
                        this.$message.warning('已输入固件路径，将优先使用输入的路径而不是选择的文件')
                    } else {
                        // 清除手动输入的路径
                        this.firmwarePath = ''
                    }
                } else {
                    console.log('📁 [FirmwareUpdate] 用户取消了文件选择或选择失败')
                }
            } catch (error) {
                console.error('❌ [FirmwareUpdate] 打开文件选择器失败:', error)
                this.$message.error('打开文件选择器失败: ' + error.message)
            }
        },

        // 处理文件选择（保留作为备用方案）
        handleFileSelect(event) {
            const file = event.target.files[0]
            if (file) {
                this.selectedFile = {
                    name: file.name,
                    path: file.path || file.name // 如果没有path属性，使用name作为备用
                }
                this.$message.info(`已选择文件: ${file.name}`)
                
                // 如果有手动输入的路径，给出提示
                if (this.firmwarePath.trim()) {
                    this.$message.warning('已输入固件路径，将优先使用输入的路径而不是选择的文件')
                }
            }
        },

        // 清除已选择的文件
        clearSelectedFile() {
            this.selectedFile = null
            this.$message.info('已清除选择的文件')
            // 如果有手动输入的路径，给出提示
            if (this.firmwarePath.trim()) {
                this.$message.warning('已输入固件路径，将优先使用输入的路径而不是上传的文件')
            }
        },

        // 监听固件路径输入
        handlePathInput() {
            // 如果同时有上传的文件，给出提示
            if (this.firmwarePath.trim() && this.selectedFile) {
                this.$message.warning('已上传文件，但将优先使用输入的固件路径')
            }
        },

        // 开始状态检查
        startStatusCheck() {
            this.clearStatusCheck()
            
            this.statusCheckTimer = setInterval(async() => {
                try {
                    const params = {
                        deviceId: this.selectedDeviceInfo.id,
                        ip: this.ipAddress,
                        port: this.port
                    }
                    
                    const response = await this.deviceTabManager.getFirmwareUpdateStatus(params)

                    if (response.code === 0) {
                        const status = response.data
                        
                        // 更新进度
                        if (status.progress !== undefined) {
                            this.updateProgress = status.progress
                        }
                        if (status.message) {
                            this.progressText = status.message
                        }

                        // 检查是否完成
                        if (status.completed) {
                            this.handleUpdateComplete(status.success)
                        }
                    }
                } catch (error) {
                    console.error('❌ [FirmwareUpdate] 获取更新状态失败:', error)
                }
            }, 2000)

            // 设置超时保护
            setTimeout(() => {
                if (this.updating) {
                    this.handleUpdateFailure('更新超时，请检查设备状态')
                }
            }, 10 * 60 * 1000) // 10分钟超时
        },

        // 清除状态检查
        clearStatusCheck() {
            if (this.statusCheckTimer) {
                clearInterval(this.statusCheckTimer)
                this.statusCheckTimer = null
            }
        },

        // 处理更新完成
        handleUpdateComplete(success) {
            this.clearStatusCheck()
            this.updating = false
            this.updateProgress = 100
            this.progressText = success ? '更新完成！' : '更新失败！'
            
            const message = success ? '固件更新成功' : '固件更新失败'
            this.$message[success ? 'success' : 'error'](message)

            // 添加更新历史记录
            this.addUpdateRecord(success)

            // 清除文件和路径
            setTimeout(() => {
                this.selectedFile = null
                this.firmwarePath = ''
                this.updateProgress = 0
                this.progressText = '准备更新...'
            }, 2000)
        },

        // 处理更新失败
        handleUpdateFailure(errorMessage) {
            this.clearStatusCheck()
            this.updating = false
            this.updateProgress = 0
            this.progressText = '更新失败'
            this.$message.error(errorMessage)

            // 添加更新历史记录
            this.addUpdateRecord(false)
        },

        // 添加更新历史记录
        addUpdateRecord(success) {
            const firmwareName = this.selectedFile ? this.selectedFile.name : this.firmwarePath.split('\\').pop() || this.firmwarePath.split('/').pop() || '未知固件'
            
            this.updateHistory.unshift({
                device: this.selectedDeviceInfo?.name || '未知设备',
                firmware: firmwareName,
                time: new Date().toLocaleString(),
                status: success ? 'success' : 'failed'
            })
        }
    }
}
</script>

<style scoped>
.firmware-update-container {
    background: white;
    border-radius: 8px;
    padding: 24px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    max-width: 800px;
    margin: 0 auto;
}
.update-header {
    margin-bottom: 24px;
    text-align: center;
}
.update-header h2 {
    margin: 0 0 8px 0;
    color: #333;
    font-size: 20px;
}
.update-header p {
    margin: 0;
    color: #666;
    font-size: 14px;
}
.upload-section h3 {
    margin-bottom: 16px;
    color: #333;
    font-size: 16px;
}
.upload-info {
    margin-top: 16px;
}
.update-actions {
    margin-top: 32px;
    text-align: center;
}
.update-progress {
    margin-top: 24px;
    padding: 16px;
    background: #f8f9fa;
    border-radius: 6px;
}
.progress-text {
    margin: 8px 0 0 0;
    text-align: center;
    color: #666;
    font-size: 14px;
}
.custom-upload-dragger {
    border: 1px dashed #d9d9d9;
    border-radius: 4px;
    padding: 20px;
    text-align: center;
    cursor: pointer;
    transition: border-color 0.3s ease;
    background-color: #fafafa;
}
.custom-upload-dragger:hover {
    border-color: #1890ff;
}
.custom-upload-dragger .upload-drag-icon {
    color: #1890ff;
    font-size: 24px;
    margin-bottom: 8px;
}
.custom-upload-dragger .upload-text {
    color: #666;
    font-size: 14px;
    margin-bottom: 4px;
}
.custom-upload-dragger .upload-hint {
    color: #999;
    font-size: 12px;
}
.file-item {
    display: flex;
    align-items: center;
    padding: 8px 0;
    border-bottom: 1px solid #eee;
}
.file-item .anticon {
    margin-right: 8px;
    color: #1890ff;
}
.file-name {
    flex-grow: 1;
    margin-right: 8px;
    color: #333;
    font-size: 14px;
}
.file-path {
    color: #999;
    font-size: 12px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    max-width: 200px; /* Adjust as needed */
}
.history-section {
    margin-top: 30px;
}
.history-section h3 {
    margin-bottom: 16px;
    color: rgba(0, 0, 0, 0.85);
    font-weight: 500;
}
:deep(.ant-list-item-meta-title) {
    margin-bottom: 4px;
}
:deep(.ant-list-item-meta-description) {
    color: rgba(0, 0, 0, 0.45);
}
:deep(.ant-tag) {
    margin-left: 8px;
}
</style> 